from pymongo import MongoClient
from elasticsearch import (
    Elasticsearch, 
    helpers,
    exceptions as es_exceptions
    )
import time
from elasticsearch_manager import ElasticsearchManager

INDEX_NAME = "component_library_module_search"
ES_HOST = 'http://127.0.0.1:9200'

# MongoDB连接设置
# mongo_client = MongoClient('mongodb://localhost:27017/')
mongo_client = MongoClient(host='127.0.0.1',port=27017)
mongo_collection = mongo_client['novapps_server']['ios_widget_component_library_module_list']

es_client = Elasticsearch(ES_HOST)

response = ElasticsearchManager.es_sync__from_mongodb(es_client=es_client, index_name=INDEX_NAME, mongo_collection=mongo_collection)
print(f"Sync complete, a total of {response[0]} records")

print("Initial data import to Elasticsearch is complete.")

# 持续监听MongoDB的变更流
while True:
    try:
        with mongo_collection.watch() as change_stream:
            for change in change_stream:
                doc_id = str(change['documentKey']['_id'])
                print(doc_id)
                
                # 处理插入操作
                if change['operationType'] in ['insert']:
                    document = change['fullDocument']
                    ElasticsearchManager.es_insert(es_client=es_client, index_name=INDEX_NAME, doc_id=doc_id, name=document.get('name', ''), tag=document.get('tag', ''))
                
                # 处理更新操作
                elif change['operationType'] == 'update':
                    # 从ES获取当前文档
                    current_document = es_client.get(index=INDEX_NAME, id=doc_id)

                    # 解析当前key字段值
                    name, tag = (current_document['_source']['key']).split(',')

                    update_fields = change['updateDescription']['updatedFields']

                    if 'name' in update_fields:
                        new_name = update_fields['name']
                        if 'tag' in update_fields:
                            # 更新name和tag部分
                            new_tag = ''.join(str(x) for x in update_fields['tag'])
                            ElasticsearchManager.es_update(es_client=es_client, index_name=INDEX_NAME, doc_id=doc_id, name=new_name, tag=new_tag)

                        else:
                            ElasticsearchManager.es_update(es_client=es_client, doc_id=doc_id, index_name=INDEX_NAME, name=new_name, tag=tag)
                    
                    elif 'tag' in update_fields:
                        # 更新tag部分，保留name部分不变
                        new_tag = update_fields['tag']
                        ElasticsearchManager.es_update(es_client=es_client, doc_id=doc_id, index_name=INDEX_NAME, name=name, tag=new_tag)
                    
                # 处理删除操作
                elif change['operationType'] == 'delete':
                    ElasticsearchManager.es_delete(es_client=es_client, doc_id=doc_id, index_name=INDEX_NAME)

                print(f"Handled {change['operationType']} operation for {doc_id}.")

    except (es_exceptions.ConnectionError, es_exceptions.TransportError) as e:
        print("Elasticsearch connection error. Retrying in 5 seconds.")
        time.sleep(5)
    except Exception as e:
        print(f"An error occurred: {e}. Retrying in 5 seconds.")
        time.sleep(5)
